#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置窗口名称
    this->setWindowTitle("客户端");
    //创建udp对象
    socket = new QUdpSocket(this);
    //连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, [=](){
        //获取数据报
        const QNetworkDatagram udp_response = socket->receiveDatagram();
        //读取数据
        const QString& data = udp_response.data();
        //写入对话框中
        ui->listWidget->addItem("服务器：" + data);
    });
}

Widget::~Widget()
{
    delete ui;
}
//发送按钮
void Widget::on_pushButton_clicked()
{
    //获取输入框的内容
    const QString& text = ui->lineEdit->text();
    //构建请求数据报
    const QString ip = "127.0.0.1";
    const quint16 port = 8082;
    QNetworkDatagram data_request(text.toUtf8(), QHostAddress(ip), port);
    //发送数据
    socket->writeDatagram(data_request);
    //更新对话框中的内容
    ui->listWidget->addItem("客户端：" + text);
    //情况输入框
    ui->lineEdit->clear();
}
